package we3d.rasterizer 
{
	import flash.display.Graphics;
	import flash.geom.Matrix;
	import we3d.material.BitmapAttributes;
	
	import we3d.material.Surface;
	import we3d.View3d;
	import we3d.mesh.Face;
	import we3d.mesh.Vertex;
	
	/**
	* Draws bitmap textures using the drawing api methods beginBitmapFill.
	*/
	public class NativeTX implements IRasterizer 
	{
		public function NativeTX () {}
		
		public var rMat:Matrix = new Matrix();
		
		public function draw (material:Surface, rc:View3d, f:Face) :void {
			
			var L:int = f.vLen;
			var sf:BitmapAttributes = BitmapAttributes(material.attributes);
			var mc:Graphics = rc.currentLayer._graphics;
			
			var a:Vertex = f.a;
			var b:Vertex = f.b;
			var c:Vertex = f.c;
			var x0:Number = a.sx;
			var y0:Number = a.sy;
			
			var sa:Number = (b.sx - x0) / sf._w;
			var sb:Number = (b.sy - y0) / sf._w;
			var sc:Number = (c.sx - x0) / sf._h;
			var sd:Number = (c.sy - y0) / sf._h;
			var t:Matrix = f.tMat;
			var r:Matrix = rMat;
			
			r.a = t.a * sa;
			r.d = t.d * sd;
			r.b = r.c = 0;
			r.ty = t.ty * sd + y0;
			r.tx = t.tx * sa + x0;
			
			if(t.b != 0 || t.c != 0 || sb != 0 || sc != 0) {
				r.a += t.b * sc;
				r.d += t.c * sb;
				r.b += t.a * sb + t.b * sd;
				r.c += t.c * sa + t.d * sc;
				r.tx += t.ty * sc;
				r.ty += t.tx * sb;
			}
			
			mc.lineStyle();
			mc.beginBitmapFill(sf._texture, r, sf.repeat, sf.smooth);
			
			mc.moveTo(x0, y0);
			mc.lineTo(b.sx, b.sy);
			
			if(L == 3) {
				mc.lineTo(c.sx, c.sy);
			}
			else if (L == 4) {
				mc.lineTo(c.sx, c.sy);
				b = f.vtxs[3];
				mc.lineTo(b.sx, b.sy);
			}
			else{
				var p:Array = f.vtxs;
				mc.lineTo(c.sx, c.sy);
				for(var i:int=3; i<L; i++) {
					b = p[i];
					mc.lineTo(b.sx, b.sy);
				}
			}
			mc.lineTo(x0, y0);
			mc.endFill();
		}
		
	}
}